package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.service.exception.GuiguException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wx
 * @version 1.0
 * @description: TODO
 * @date 2024/11/6 11:21
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //校验验证码
        //从redis中取出验证码
        String validateCode = redisTemplate.opsForValue().get("user:login:validatecode:" + loginDto.getCodeKey());
        //获取用户输入的验证码
        String inputCaptcha = loginDto.getCaptcha();
//        if (!inputCaptcha.equalsIgnoreCase(validateCode)) {
        if (StrUtil.isEmpty(validateCode) || !StrUtil.equalsIgnoreCase(validateCode, inputCaptcha)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //根据用户名数据库查询用户信息
        SysUser sysUser = sysUserMapper.selectSysUserByUserName(loginDto.getUserName());
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //获取用户输入的明文密码
        String password = loginDto.getPassword();
        //加密密码 MD5
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        //校验密码
        if (!md5DigestAsHex.equalsIgnoreCase(sysUser.getPassword())) {
//            throw new RuntimeException("用户名或密码错误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        //存储到redis key
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser), 5, TimeUnit.MINUTES);
        //封装数据
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token(null);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String sysUserJson = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(sysUserJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void loginOut(String token) {
        redisTemplate.delete("user:login:" + token);

    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        //设置分页条件
        PageHelper.startPage(pageNum, pageSize);
        //查询用户列表
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto);
        //封装分页对象
        return new PageInfo<SysUser>(sysUserList);
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断是否存在新增的用户
        SysUser user = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
        if (user != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码加密
        String userPassword = sysUser.getPassword();
        String password = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        sysUser.setPassword(password);
        //状态赋值
        sysUser.setStatus(0);
        //新增
        sysUserMapper.saveSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        //判断是否存在用户
        SysUser user = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
//        if (user != null) {
//            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
//        }
        sysUserMapper.updateSysUser(sysUser);
    }

    /**
     * 根据id删除用户
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }
}
